package com.wcfsy.wechat.wx.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wcfsy.wechat.wx.entity.Course;
import com.wcfsy.wechat.wx.entity.TemplateData;
import com.wcfsy.wechat.wx.entity.WechatUserInfo;
import com.wcfsy.wechat.wx.sys.dao.CourseDao;
import com.wcfsy.wechat.wx.util.DateStyle;
import com.wcfsy.wechat.wx.util.DateUtil;
import com.wcfsy.wechat.wx.util.PushMessage;
import com.wcfsy.wechat.wx.util.StringUtil;

@Service("courseService")
public class CourseService {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private final String tempId = "31GwMOYOz49O38mwc4kmNXwpp7M1I4KH8hKmv4CvLzU"; 
	
	private final String url = "http://www.wfcsy.com";
	
	@Resource
	private PushMessage pushMessage;
	
	@Resource
	private CourseDao  courseDao;
	
	public void pushCourseTime(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("pushTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
		List<Course> list = courseDao.findPushTimeList(map);
		int length = list.size() > 0 ? list.size() : 0;
		Course course = null;
		for (int i = 0; i < length; i++) {
			course = new Course();
			List<WechatUserInfo> users = courseDao.getCourseUser(course.getType());
			int usersLength = users.size() > 0 ? users.size() : 0;
			for (int j = 0; j < usersLength; j++) {
				Map<String,TemplateData> templateMap = new HashMap<String,TemplateData>();
				if(StringUtils.isNotEmpty(users.get(j).getNickname())){
					PushMessage.addTemplateData("first","亲爱的"+StringUtil.decode(users.get(j).getNickname())+"，您明天有课上哟！",templateMap);
				}else{
					PushMessage.addTemplateData("first","亲爱的五次方学员，您明天有课上哟！",templateMap);
				}
				PushMessage.addTemplateData("keyword1",course.getTime(),templateMap);
				PushMessage.addTemplateData("keyword2","五次方基地",templateMap);
				PushMessage.addTemplateData("keyword3",course.getTeacher(),templateMap);
				PushMessage.addTemplateData("keyword3",course.getName(),templateMap);
				PushMessage.addTemplateData("remark",course.getRemark(),templateMap);
				pushMessage(users.get(j).getOpenid(),tempId,templateMap);
			}
			
		}
	}
	
	private  void pushMessage(String openId,String templateId,Map<String,TemplateData> map){
		pushMessage.sendTemplateMessage(openId, templateId, map, url);
	}
	
}
